<?php
class ComTool
{
	// 串口句柄
	private $ComHandle = null;
	
	// 串口打开是否成功
	private $OpenFlg = false;
	
	/*
	 * 打开串口
	 */
	function open()
	{
		// 设置串口参数
		exec('mode COM1: baud=9600 data=8 stop=1 parity=n xon=off');
		$this->ComHandle = dio_open('COM1:',O_RDWR);
		if(!$this->ComHandle)
		{
			$OpenFlg = false;
			die("串口打开失败，可能是其他程序占用了！");
		}
		
		// 打开成功
		$OpenFlg = true;
	}
	
	/*
	 * 读取串口数据
	 */
	function read($cmd){
		
		if($this->OpenFlg){
			// 发送的命令
			dio_write($this->ComHandle,$cmd.chr(13));

			$response = dio_read($this->ComHandle, 200);
			return substr($response,1,strpos($response,13));
		}else{
			$this->open();
			
			// 发送的命令
			dio_write($this->ComHandle,$cmd.chr(13));
			
			$response = dio_read($this->ComHandle, 200);
			return substr($response,1,strpos($response,13));
		}
	}
	
	/*
	 * 写取串口数据
	 */
	function write($cmd){
		
		if($this->OpenFlg){
			// 发送的命令
			dio_write($this->ComHandle,$cmd.chr(13));
		}else{
			// 发送的命令
			dio_write($this->ComHandle,$cmd.chr(13));
		}
	}
}